import time
from selenium import webdriver
from selenium.webdriver.common.by import By
# 导入显式等待
from selenium.webdriver.support.wait import WebDriverWait
# 导入expected_conditions预期条件并起别名
from selenium.webdriver.support import expected_conditions as EC
# 导入异常类型
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, NoSuchElementException


class Base:
    """
    基础类,封装selenium基础用法,作为page包里的类的父类
    """

    def __init__(self, browser):
        """
        打开浏览器,设置driver对象
        """
        if browser == 'chrome':
            self.driver = webdriver.Chrome()
        elif browser == 'firefox':
            self.driver = webdriver.Firefox()
        elif browser == 'edge':
            self.driver = webdriver.Edge()
        elif browser == 'ie':
            self.driver = webdriver.Ie()
        else:
            self.driver = None
            print('不支持该浏览器')

    def get(self, url):
        """
        请求目标网址
        """
        self.driver.maximize_window()  # 最大化窗口

        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('输入的地址不正确')

    def find_element(self, locator):
        """
        定位元素
        locator = (By.xxx, value)  元组
        *locator = By.xxx, value
        """
        try:
            return self.driver.find_element(*locator)
        except NoSuchElementException:
            print('元素定位失败')

    def click(self, locator):
        """
        点击操作
        """
        # 先调用前面定义的find_element方法 定位元素
        element = self.find_element(locator)
        # 判断元素定位成功,点击元素
        if element is not None:
            element.click()
        else:
            print('元素定位失败')

    def get_attribut(self, locator, param):
        """
        获取元素属性
        """
        # 先调用前面定义的find_element方法, 定位元素
        element = self.find_element(locator)
        # 判断元素定位成功, 获取元素属性
        if element is not None:
            attri = element.get_attribute(param)
            if attri is not None:
                print(attri)
            else:
                print('不存在此属性')
        else:
            print('元素定位失败')

    def refresh(self):
        """
        刷新浏览器
        """
        self.driver.refresh()

    def back(self):
        """
        浏览器后退
        """
        self.driver.back()

    def forward(self):
        """
        浏览器前进
        """
        self.driver.forward()

    def quit(self):
        """
        退出浏览器
        """
        self.driver.quit()


if __name__ == '__main__':
    # 创建Base类的实例, 设置driver对象
    test = Base('chrome')
    # 提交网址
    test.get('https://ecshop.test2.shopex123.com/user.php')
    # 查看元素属性
    test.get_attribut((By.PARTIAL_LINK_TEXT, '忘记密码'), 'class')
    # 点击元素
    test.click((By.PARTIAL_LINK_TEXT, '忘记密码'))
    time.sleep(1)
    # 浏览器后退
    test.back()
    time.sleep(1)
    # 浏览器前进
    test.forward()
    time.sleep(1)
    # 浏览器刷新
    test.refresh()
    time.sleep(1)
    # 退出浏览器
    test.quit()


